﻿#include "mainwindow.h"

#include <QFontDialog>
#include <qfont_save_load.h>
#include <para.h>
extern MyPARA my_para;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    logger->info("start program");

     setWindowTitle("2025/08/22");
    initHalconGpu();

    logger_user->flush_on(spdlog::level::info);
    QString m_model_dir = QCoreApplication::applicationDirPath() + "/function";

    bool ret =loadPara();
    if(ret == false)
    {
        QMessageBox::critical(nullptr, "para", "ini no");
        qApp->quit();
    }
    QString qstring_path = m_type_dir + "/" + m_type_name + "/para.db";

    initQSQLITE(qstring_path);

    if (m_login_dialog == nullptr)
    {
        m_login_dialog = new Login_Dialog();
        m_login_dialog->setModal(true);
        connect(m_login_dialog->m_login_button, &QPushButton::clicked, this, &MainWindow::login);
    }

    if (m_qwidget_user == nullptr)
    {
        m_qwidget_user = new UserManager();
        m_qwidget_user->m_path = m_exe_directory + "/para/users.dat";
        m_qwidget_user->loadFromFile();
        m_qwidget_user->setModal(true);
    }
    if (m_qwidget_admin == nullptr)
    {
        m_qwidget_admin = new UserManager();
        m_qwidget_admin->m_path = m_exe_directory + "/para/admin.dat";
        m_qwidget_admin->loadFromFile();
        m_qwidget_admin->setModal(true);
    }

    m_store_recipe_dialog.m_dir =  m_type_dir;
    m_store_recipe_dialog.setModal(true);
    connect(m_store_recipe_dialog.m_qpushbutton_store, &QPushButton::clicked, this, &MainWindow::storeRecipe);

    m_load_recipe_dialog.m_dir =  m_type_dir;
    m_load_recipe_dialog.setModal(true);
    connect(m_load_recipe_dialog.m_qpushbutton_load, &QPushButton::clicked, this, &MainWindow::loadRecipe);

    initMainWindow();


    //检测类初始化
    {
        m_qdialog_detection = new QDialog(this);
        m_qdialog_detection->setModal(true);
        m_tabwidget_detection = new QTabWidget(m_qdialog_detection);
        m_tabwidget_detection->move(0, 0);
        m_tabwidget_detection->setFixedSize(1920, 1000);
        for (int i = 0; i < m_camera_number; i++)
        {
            list<uint> vector_result;
            m_result_data.push_back(vector_result);
            m_vector_time.push_back(0);
            QtThreadProcess* pQtThreadProcess = new QtThreadProcess();
            pQtThreadProcess->m_camera_index = i;
            QString section = "camera" + QString::number(i) + "/";
            pQtThreadProcess->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();
            pQtThreadProcess->m_detection_number = m_settings_para->value(section + "m_detection_number", 1).toInt();
            pQtThreadProcess->m_image_dir = m_settings_para->value(section + "m_image_dir", "").toString();
            pQtThreadProcess->m_times = m_settings_para->value(section + "m_times", 1).toInt();

            my_para.m_vector_camera_name.push_back(pQtThreadProcess->m_camera_name);
            connect(pQtThreadProcess, &QtThreadProcess::sendDetectionResult, this, &MainWindow::showResult, Qt::QueuedConnection);

            QString qstring_dir = m_type_dir + "/" + m_type_name  ;
            pQtThreadProcess->m_function = new Function(nullptr, qstring_dir, i);


            connect(pQtThreadProcess->m_function->m_pushbutton_return, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            m_tabwidget_detection->addTab(pQtThreadProcess->m_function, pQtThreadProcess->m_camera_name);

            pQtThreadProcess->start();
            m_vector_detection_thread.push_back(pQtThreadProcess);
        }
    }
//    //dl_3初始化////////////////////////////////////
//    dl_3_init();
    //相机类初始化
    {
        m_qdialog_camera = new QDialog(this);
        m_qdialog_camera->setModal(true);
        m_tabwidget_camera = new QTabWidget(m_qdialog_camera);
        m_tabwidget_camera->move(0, 0);
        QRect desktop_rect = QApplication::desktop()->geometry();
        double ratio_x = desktop_rect.width() / 1920.0;
        double ratio_y = desktop_rect.height() / 1080.0;

        move(0, 0);
        m_tabwidget_camera->setFixedSize(600 * ratio_x, 1010 * ratio_y);
        for (int i = 0; i < m_camera_number; i++)
        {

            QString qstring_dir = m_type_dir + "/" + m_type_name  ;
            CameraBaseQDialog* p = new CameraBaseQDialog(nullptr, qstring_dir, i);
            connect(p->m_qpushbutton_hide, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            QString section = "camera" + QString::number(i) + "/";
            p->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();



            m_tabwidget_camera->addTab(p, p->m_camera_name);
            if (m_online == 1)
            {
                //在线检测
                logger->info("camera connect");
                p->m_SN = m_settings_para->value(section + "m_SN", QString::number(i)).toString();


                bool result = p->initCamera(p->m_camera_name, callback, m_vector_detection_thread[i]);
                if (result == false)
                {
                    QString StringMessage = QString("camera %1 failure").arg(p->m_camera_name);
                    QMessageBox::information(nullptr, p->m_camera_name, StringMessage);
                }
            }
            if (m_online == 0)
            {
                //离线检测
                 p->m_image_dir = m_settings_para->value(section + "m_image_dir", QString::number(i)).toString();
                QDir dir(p->m_image_dir);
                if (!dir.exists())
                {
                    QMessageBox::critical(nullptr, p->m_image_dir, "离线测试文件夹不存在");
                }
                else
                {
                    dir.setFilter(QDir::Files | QDir::NoSymLinks);
                    QStringList filters;
                    filters << "*.bmp" << "*.jpg" << "*.png";
                    dir.setNameFilters(filters);

                    QStringList  string_list = dir.entryList();
                    foreach(QString  var, string_list) {
                        m_vector_detection_thread[i]->m_images_path.push_back(m_vector_detection_thread[i]->m_image_dir + "\\" + var);
                    }
                }
                QTimer* m_qtimer_offline = new QTimer(this);
                connect(m_qtimer_offline, &QTimer::timeout, this, [=]() {
                    m_vector_detection_thread[i]->m_image_index++;
                    if (m_vector_detection_thread[i]->m_images_path.size() > 0)
                    {
                        Mat image_read_file;
                        image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString(),IMREAD_UNCHANGED);
                        if (!image_read_file.empty())
                        {
//							HObject hobject_iamge = matToHImage(image_read_file);
                            callback(image_read_file, m_vector_detection_thread[i]);
                           /* m_vector_detection_thread[i]->m_camera_index = i;
                            m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);*/
                        }
                    }
                    });
                m_qtimer_offline->start(5000);//固定频率读取离线测试图像
            }
            m_vector_camera.push_back(p);
        }
    }
    //处理类和相机类相互关联
    for (int i = 0; i < m_camera_number; i++)
    {
        connect(m_vector_detection_thread[i], &QtThreadProcess::sendShowImage, m_vector_camera[i], &CameraBaseQDialog::showImage);

    }
    //login
//      m_qpushbutton_stop_detection->setDisabled(true);
//      m_Login_Dialog = new Login_Dialog(this);
//      m_Login_Dialog->setModal(true);
//      connect(m_Login_Dialog->m_login_button, &QPushButton::clicked, this,&MainWindow::login);

    ////tcpsocket
    //{
    //    m_qtcpsocket_unused_used = m_settings_para->value("para/m_qtcpsocket_unused_used", 0).toInt();
    //    m_qtcpsocket_ip = m_settings_para->value("para/m_qtcpsocket_ip", "192.168.2.1").toString();
    //    m_qtcpsocket_port = m_settings_para->value("para/m_qtcpsocket_port", 502).toInt();
    //    if (m_qtcpsocket_unused_used > 0)
    //    {
    //        m_qtcpsocket = new QTcpSocket();
    //        m_qtcpsocket->connectToHost(m_qtcpsocket_ip, m_qtcpsocket_port, QTcpSocket::ReadWrite);
    //        if (!m_qtcpsocket->waitForConnected(100)) {
    //            QMessageBox::information(nullptr, "TcpSocket", m_qtcpsocket_ip + "" + QString::number(m_qtcpsocket_port));
    //        }
    //        else {
    //            connect(m_qtcpsocket, &QTcpSocket::readyRead, this, [=]() {
    //                QByteArray buffer_read = m_qtcpsocket->readAll();
    //                QString qstring_read = QString(buffer_read);
    //                });
    //        }
    //    }
    //}

    //modbus
    {
        m_modbus_ip = m_settings_para->value("para/m_modbus_ip", "192.168.2.1").toString();
        m_modbus_port = m_settings_para->value("para/m_modbus_port", 502).toInt();

        m_plc_write = m_settings_para->value("para/m_plc_write",0).toInt();
        m_plc_result1 = m_settings_para->value("para/m_plc_result1",0).toInt();
        m_plc_result2 = m_settings_para->value("para/m_plc_result2",0).toInt();

        for(int i=0;i<m_camera_number;i++)
        {
            QString section = "camera" + QString::number(i) + "/";
            m_plc_trigger.push_back(m_settings_para->value(section+"m_plc_trigger","").toInt());
            m_plc_result.push_back(m_settings_para->value(section+"m_plc_result","").toInt());
        }
        m_modbus_tcp = modbus_new_tcp(m_modbus_ip.toStdString().c_str(), m_modbus_port);
        if (m_modbus_tcp == nullptr)
            QMessageBox::information(nullptr, "", "PLC error");
        else
            if (modbus_connect(m_modbus_tcp) == -1)
                QMessageBox::information(nullptr, "", "PLC error ");
        m_timer_plc = new QTimer(this);

        connect(m_timer_plc, &QTimer::timeout, this, &MainWindow::timerPLC);


        //去除相机拍照信号
        for(int i=0;i< m_camera_number;i++)
        {
            uint16_t plc_write_value = 0  ;
            modbus_write_registers(m_modbus_tcp,m_plc_trigger[i],1,&plc_write_value);
        }
        m_timer_plc->start(100);
    }




    m_timer_data = new QTimer(this);

    connect(m_timer_data, &QTimer::timeout, this, &MainWindow::timerData);
    m_timer_data->start(1000);


   /* m_timer_camera2 = new QTimer(this);

    connect(m_timer_camera2, &QTimer::timeout, this, &MainWindow::timerCamera2);
    m_timer_data->start(1000);*/


    //存图线程开始
    m_save_image_thread = new SaveImageThread();
    m_save_image_thread->run();

    m_qtime_start = QDateTime::currentDateTime();


    //检测开始
    startDetection();
}

MainWindow::~MainWindow()
{


    logger->warn("程序关闭");
    //for (int i = 0; i < m_camera_number; i++)
    //{
    //          if(m_online==1)
    //              m_vector_camera[i]->m_camera_interface->unInitCamera();
    //          /*for(uint j=0;j<m_vector_detection_thread.size();j++)
    //              m_vector_detection_thread[i]->quit();*/
    //}
//    m_serial->quit();
}

void MainWindow::clickCamera()
{
    if(my_para.m_login_privilege <1)
    {
        QMessageBox::warning(nullptr, "", "login no permissions");
        return;
    }
//    if (m_vector_detection_thread[0]->m_proess_state == false)
//    {
//        for (int i = 0; i < m_camera_number; i++)
//        {
//            m_vector_detection_thread[i]->m_only_show_state = true;
//        }
        m_qdialog_camera->show();
//    }
//    else
//    {
//        QMessageBox::warning(nullptr, "Title", "fist stop detection");
//    }
}

void MainWindow::clickPara()
{
    if(my_para.m_login_privilege <1)
    {
        QMessageBox::warning(nullptr, "", "login no permissions");
        return;
    }
//    if (m_vector_detection_thread[0]->m_proess_state == false)
//    {
        m_qdialog_detection->show();
        //              m_vector_detection_thread->m_function
        //              m_detection_para_tab_widget->setCurrentIndex(0);

        //              m_detection_para_tab_widget->raise();
//    }
//    else
//    {
//        QMessageBox::warning(nullptr, "", "fist stop detection");
//    }
}

void MainWindow:: clickUser()
{
    if(my_para.m_login_privilege <2)
    {
        QMessageBox::warning(nullptr, "", "login no permissions");
        return;
    }
    m_qwidget_user->show() ;
}

void MainWindow::clickAdmin()
{
    if (my_para.m_login_privilege < 3)
    {
        QMessageBox::warning(nullptr, "", "login no permissions");
        return;
    }
    m_qwidget_admin->show();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox::information(nullptr, "", "no exit from here");
    event->ignore();
}

void MainWindow::closeSoftware()
{
    int ok = QMessageBox::warning(this, ("exit!"), ("are you sure？"), QMessageBox::Yes, QMessageBox::No);
    if (ok == QMessageBox::Yes)
    {
        m_settings_para->setValue("para/geometry", saveGeometry());
        m_settings_para->setValue("para/state", saveState());
        m_settings_para->sync();
        delete m_settings_para;
//        dl_3_end();
        qApp->quit();
    }
}

void MainWindow::initImageControl()
{
    m_image_widget = new QWidget();
    setCentralWidget(m_image_widget);
    QGridLayout* qgrid = new QGridLayout();
    //qgridlayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    qgrid->setSpacing(1);
    qgrid->setMargin(1);
    qgrid->setColumnStretch(0, 1);
    qgrid->setColumnStretch(1, 1);
    qgrid->setColumnStretch(2, 1);
    qgrid->setRowStretch(0, 1);
    qgrid->setRowStretch(1, 1);
    m_image_widget->setLayout(qgrid);
    int step = (m_camera_number+1)/2;
    for(int i=0;i<m_camera_number;i++)
    {
        ShowQLabel* p = new ShowQLabel(m_image_widget);

        p->setMinimumSize(200, 200);
       // QPictureBox* p = new QPictureBox(m_image_widget);
        m_vector_show_qlabel.push_back(p);
        qgrid->addWidget(p,i/step,i%step,1,1);
    }
    if (m_camera_number != 5)
    {
        QMessageBox::warning(nullptr, "", "camera not 5");
        qApp->quit();
    }

    if(m_camera_number==5)
    {
        QWidget* p = new QWidget(m_image_widget);
        p->setMinimumSize(200, 200);
        int index =0;

        QGridLayout *qgridLayout = new QGridLayout();
        p->setLayout(qgridLayout);

        QLabel* plabel  = new QLabel();
        plabel->setText("Recipe ");
        qgridLayout->addWidget(plabel,index,0);
        plabel  = new QLabel();
        plabel->setText(m_type_name);
        qgridLayout->addWidget(plabel,index,1,1,2);
        index++;

        plabel  = new QLabel();
        plabel->setText("Time");
        qgridLayout->addWidget(plabel,index,0);
        m_qlabel_time  = new QLabel();
        m_qlabel_time->setText("");
        qgridLayout->addWidget(m_qlabel_time,index,1);
        index++;

        plabel  = new QLabel();
        plabel->setText("Cycle Time");
        qgridLayout->addWidget(plabel,index,0);
        m_qlabel_cycle_time  = new QLabel();
        m_qlabel_cycle_time->setText("");
        qgridLayout->addWidget(m_qlabel_cycle_time,index,1);
        index++;

        plabel  = new QLabel();
        plabel->setText("Qualified Quantity");
        qgridLayout->addWidget(plabel,index,0);
        m_qlabel_qualified_quantity  = new QLabel();
        m_qlabel_qualified_quantity->setText("0");
        qgridLayout->addWidget(m_qlabel_qualified_quantity,index,1);
        QPushButton* pbutton  = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton,&QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }
            m_qualified_quantity=0;
            m_qlabel_qualified_quantity->setText(QString::number(m_qualified_quantity));
        });
        qgridLayout->addWidget(pbutton,index,2);
        index++;

        plabel  = new QLabel();
        plabel->setText("Defective Quantity");
        qgridLayout->addWidget(plabel,index,0);
        m_qlabel_defective_quantity  = new QLabel();
        m_qlabel_defective_quantity->setText("0");
        qgridLayout->addWidget(m_qlabel_defective_quantity,index,1);
        pbutton  = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton,&QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }
            m_defective_quantity=0;
            m_qlabel_defective_quantity->setText(QString::number(m_defective_quantity));
        });
        qgridLayout->addWidget(pbutton,index,2);
        index++;

        plabel  = new QLabel();
        plabel->setText("OperatingTime");
        qgridLayout->addWidget(plabel,index,0);
        m_qlabel_operating_time  = new QLabel();
        m_qlabel_operating_time->setText("");
        qgridLayout->addWidget(m_qlabel_operating_time,index,1);
        pbutton  = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton,&QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }
            m_qtime_start = QDateTime::currentDateTime();
            m_qlabel_operating_time->setText("0h");
        });
        qgridLayout->addWidget(pbutton,index,2);
        index++;

        plabel = new QLabel();
        plabel->setText("Scan 1 NG");
        qgridLayout->addWidget(plabel, index, 0);
        m_qlabel_camera0 = new QLabel();
        m_qlabel_camera0->setText("0");
        qgridLayout->addWidget(m_qlabel_camera0, index, 1);
        pbutton = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton, &QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }
            m_vector_detection_thread[0]->m_ng0_count = 0;
            m_qlabel_camera0->setText(QString::number(m_vector_detection_thread[0]->m_ng0_count));
        });
        qgridLayout->addWidget(pbutton, index, 2);
        index++;

        plabel = new QLabel();
        plabel->setText("Scan 2 NG");
        qgridLayout->addWidget(plabel, index, 0);
        m_qlabel_camera1 = new QLabel();
        m_qlabel_camera1->setText("0");
        qgridLayout->addWidget(m_qlabel_camera1, index, 1);
        pbutton = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton, &QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }

            m_vector_detection_thread[1]->m_ng0_count = 0;
            m_qlabel_camera1->setText(QString::number(0));
        });
        qgridLayout->addWidget(pbutton, index, 2);
        index++;

        plabel = new QLabel();
        plabel->setText("Flank NG");
        qgridLayout->addWidget(plabel, index, 0);
        m_qlabel_camera2 = new QLabel();
        m_qlabel_camera2->setText("0");
        qgridLayout->addWidget(m_qlabel_camera2, index, 1);
        pbutton = new QPushButton();
        pbutton->setText("Clear");
        connect(pbutton, &QPushButton::clicked, this, [=]() {
            if (my_para.m_login_privilege < 2)
            {
                QMessageBox::warning(nullptr, "", "login no permissions");
                return;
            }
            m_vector_detection_thread[2]->m_ng0_count = 0;
            m_qlabel_camera2->setText(QString::number(0));
        });
        qgridLayout->addWidget(pbutton, index, 2);
        index++;

        //top
        {
            plabel = new QLabel();
            plabel->setText("Top0");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera3_0 = new QLabel();
            m_qlabel_camera3_0->setText("0");
            qgridLayout->addWidget(m_qlabel_camera3_0, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[3]->m_ng0_count = 0;
                m_qlabel_camera3_0->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;

            plabel = new QLabel();
            plabel->setText("Top1");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera3_1 = new QLabel();
            m_qlabel_camera3_1->setText("0");
            qgridLayout->addWidget(m_qlabel_camera3_1, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[3]->m_ng1_count = 0;
                m_qlabel_camera3_1->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;

            plabel = new QLabel();
            plabel->setText("Top2");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera3_2 = new QLabel();
            m_qlabel_camera3_2->setText("0");
            qgridLayout->addWidget(m_qlabel_camera3_2, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[3]->m_ng2_count = 0;
                m_qlabel_camera3_2->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;
        }
        //bottom
        {
            plabel = new QLabel();
            plabel->setText("Bottom0");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera4_0 = new QLabel();
            m_qlabel_camera4_0->setText("0");
            qgridLayout->addWidget(m_qlabel_camera4_0, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[4]->m_ng0_count = 0;
                m_qlabel_camera4_0->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;

            plabel = new QLabel();
            plabel->setText("Bottom1");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera4_1 = new QLabel();
            m_qlabel_camera4_1->setText("0");
            qgridLayout->addWidget(m_qlabel_camera4_1, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[4]->m_ng1_count = 0;
                m_qlabel_camera4_1->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;

            plabel = new QLabel();
            plabel->setText("Bottom2");
            qgridLayout->addWidget(plabel, index, 0);
            m_qlabel_camera4_2 = new QLabel();
            m_qlabel_camera4_2->setText("0");
            qgridLayout->addWidget(m_qlabel_camera4_2, index, 1);
            pbutton = new QPushButton();
            pbutton->setText("Clear");
            connect(pbutton, &QPushButton::clicked, this, [=]() {
                if (my_para.m_login_privilege < 2)
                {
                    QMessageBox::warning(nullptr, "", "login no permissions");
                    return;
                }
                m_vector_detection_thread[4]->m_ng2_count = 0;
                m_qlabel_camera4_2->setText(QString::number(0));
            });
            qgridLayout->addWidget(pbutton, index, 2);
            index++;
        }
        pbutton = new QPushButton();
        pbutton->setText("login");
        connect(pbutton, &QPushButton::clicked, this, [=]() {
            m_login_dialog->show();
        });
        qgridLayout->addWidget(pbutton, index, 0);


        pbutton = new QPushButton();
        pbutton->setText("user");
        qgridLayout->addWidget(pbutton,index,1);
        connect(pbutton, &QPushButton::clicked, this, &MainWindow::clickUser);

        pbutton = new QPushButton();
        pbutton->setText("admin");
        qgridLayout->addWidget(pbutton, index, 2);
        connect(pbutton, &QPushButton::clicked, this, &MainWindow::clickAdmin);



        qgrid->addWidget(p, 1, 2, 1, 1);
    }


}

void MainWindow::initShowTable()
{
    m_qdockwidget_show_table = new QDockWidget(("ALarm"), this);
    m_qdockwidget_show_table->setObjectName("ALarm");
    m_qdockwidget_show_table->setAllowedAreas(Qt::BottomDockWidgetArea);
    m_qdockwidget_show_table->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable);
    addDockWidget(Qt::BottomDockWidgetArea, m_qdockwidget_show_table);
    menuBar()->addMenu(("Alarm"))->addAction(m_qdockwidget_show_table->toggleViewAction());

    m_show_table_data = new QStandardItemModel(m_qdockwidget_show_table);
    m_show_table_data->setColumnCount(2);
    m_show_table_data->setRowCount(100);
    QStringList qstringlist;
    qstringlist<<"time"<<"error message";
    m_show_table_data->setHorizontalHeaderLabels(qstringlist);

    m_show_table = new QTableView(m_qdockwidget_show_table);
    m_show_table->setModel(m_show_table_data);
//    m_show_table->setStyleSheet(".QTableView { border: none;color:white;"
//                                   "background-color:transparent;"
//                                   "selection-background-color:skyblue}"); //for demo purposes
//    m_show_table->horizontalHeader()->setStyleSheet("QHeaderView::section{color:white;background:skyblue;}"); // 设置表头背景色
//    m_show_table->verticalHeader()->setStyleSheet("QHeaderView::section{color:white;background:skyblue;}"); // 设置表头背景色
    m_show_table->verticalHeader()->setVisible(false);
    m_show_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_show_table->setEditTriggers(QAbstractItemView::NoEditTriggers);		// 设置不可编辑
    m_show_table->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_qdockwidget_show_table->setWidget(m_show_table);
}

void MainWindow::initdockPannel()
{
    m_qdockwidget_pannel = new QDockWidget(("Pannel"), this);
    m_qdockwidget_pannel->setObjectName("pannel");
    m_qdockwidget_pannel->setAllowedAreas(Qt::LeftDockWidgetArea);
    m_qdockwidget_pannel->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable);
    addDockWidget(Qt::LeftDockWidgetArea, m_qdockwidget_pannel);
    menuBar()->addMenu(("Pannel"))->addAction(m_qdockwidget_pannel->toggleViewAction());

    QWidget* qwidget = new QWidget();
    m_qdockwidget_pannel->setWidget(qwidget);

    QVBoxLayout* qvobxlayout = new QVBoxLayout();
    qvobxlayout->setSpacing(10);
    qwidget->setLayout(qvobxlayout);

    m_qpushbutton_start_detection = new QPushButton();
    m_qpushbutton_start_detection->setText("Start");
    qvobxlayout->addWidget(m_qpushbutton_start_detection);
    connect(m_qpushbutton_start_detection, &QPushButton::clicked, this, &MainWindow::startDetection);

    m_qpushbutton_stop_detection = new QPushButton();
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setText("Stop");
    qvobxlayout->addWidget(m_qpushbutton_stop_detection);
    connect(m_qpushbutton_stop_detection, &QPushButton::clicked, this, &MainWindow::stopDetection);

    m_qpushbutton_camera = new QPushButton();
    m_qpushbutton_camera->setText("Camera");
    qvobxlayout->addWidget(m_qpushbutton_camera);
    connect(m_qpushbutton_camera, &QPushButton::clicked, this, &MainWindow::clickCamera);

    m_qpushbutton_para = new QPushButton();
    m_qpushbutton_para->setText("Para");
    qvobxlayout->addWidget(m_qpushbutton_para);
    connect(m_qpushbutton_para, &QPushButton::clicked, this, &MainWindow::clickPara);




    m_qpushbutton_open_image_dir = new QPushButton();
    m_qpushbutton_open_image_dir->setText("Images");
    qvobxlayout->addWidget(m_qpushbutton_open_image_dir);
    connect(m_qpushbutton_open_image_dir, &QPushButton::clicked, this, [=](){
        if (my_para.m_login_privilege < 1)
        {
            QMessageBox::warning(nullptr, "", "login no permissions");
            return;
        }
        QDesktopServices::openUrl(QUrl(m_settings_para->value("para/m_save_image_dir", "").toString(), QUrl::TolerantMode));
    });


    m_qpushbutton_open_log_dir = new QPushButton();
    m_qpushbutton_open_log_dir->setText(tr("UserLogs"));
    qvobxlayout->addWidget(m_qpushbutton_open_log_dir);
    connect(m_qpushbutton_open_log_dir, &QPushButton::clicked, this, [=](){
        if (my_para.m_login_privilege < 2)
        {
            QMessageBox::warning(nullptr, "", "login no permissions");
            return;
        }
        QDesktopServices::openUrl(QUrl("logger_user" , QUrl::TolerantMode));
    });

    m_qpushbutton_open_type_dir = new QPushButton();
    m_qpushbutton_open_type_dir->setText("Load");
    qvobxlayout->addWidget(m_qpushbutton_open_type_dir);
    connect(m_qpushbutton_open_type_dir, &QPushButton::clicked, this, [=](){
        if(my_para.m_login_privilege < 1)
        {
            QMessageBox::warning(nullptr, "", "login no permissions");
            return;
        }
        m_load_recipe_dialog.updateQListView();
        m_load_recipe_dialog.show();
    });

    m_qpushbutton_save_type_dir = new QPushButton();
    m_qpushbutton_save_type_dir->setText("Store");
    qvobxlayout->addWidget(m_qpushbutton_save_type_dir);
    connect(m_qpushbutton_save_type_dir, &QPushButton::clicked, this, [=](){
        if (my_para.m_login_privilege < 2)
        {
            QMessageBox::warning(nullptr, "", "login no permissions");
            return;
        }
        m_store_recipe_dialog.updateQListView();
        m_store_recipe_dialog.show();
    });


    m_qpushbutton_open_help = new QPushButton();
    m_qpushbutton_open_help->setText("Help");
    qvobxlayout->addWidget(m_qpushbutton_open_help);
    connect(m_qpushbutton_open_help, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl::fromLocalFile(m_para_dir + "/help.pdf"));
    });

    m_qpushbutton_exit = new QPushButton();
    m_qpushbutton_exit->setText("Exit");
    qvobxlayout->addWidget(m_qpushbutton_exit);
    connect(m_qpushbutton_exit, &QPushButton::clicked, this, &MainWindow::closeSoftware);

//    qvobxlayout->addStretch();


}

void MainWindow::initMainWindow()
{

    loadFont();



    initdockPannel();
    initImageControl();
    initShowTable();

    menuBar()->addAction("Font", this, &MainWindow::setFont);




    restoreGeometry(m_settings_para->value("para/geometry").toByteArray());
    restoreState(m_settings_para->value("para/state").toByteArray());
}

bool MainWindow::loadPara()
{
    m_exe_directory = QCoreApplication::applicationDirPath();
    m_para_dir = m_exe_directory + "/para";
    QString path;
    path=   m_para_dir + "/para.ini";
    //创建配置文件操作对象
    m_settings_para = new QSettings(path, QSettings::IniFormat);
    m_settings_para->setIniCodec("UTF-8");
    m_save_data_dir=m_settings_para->value("para/m_save_data_dir","").toString();
    m_type_dir =  m_settings_para->value("para/m_type_dir","").toString();
    m_type_dir =  m_exe_directory + "/" + m_type_dir;
    m_type_name =  m_settings_para->value("para/m_type_name","").toString();
    m_camera_number=m_settings_para->value("para/m_camera_number",1).toInt();
    m_online=m_settings_para->value("para/m_online",-1).toInt();
    m_save_image_dir = m_settings_para->value("para/m_save_image_dir", "").toString();
    return true;
}

void MainWindow::login()
{
    if (my_para.m_login_privilege == 0)
    {
        if (m_login_dialog->m_qcombox_level->currentIndex()==0)
        {

            bool state = m_qwidget_user->m_userDatabase.values().contains(m_login_dialog->m_passward_edit->text());
            if(!state)
            {
                QMessageBox::critical(nullptr,"error", "paasord " + m_login_dialog->m_passward_edit->text() + " no exit");
                return;
            }
			
			QMap<QString, QString>::iterator it;
			for (it = m_qwidget_user->m_userDatabase.begin(); it != m_qwidget_user->m_userDatabase.end(); ++it) {
				if (it.value() == m_login_dialog->m_passward_edit->text())
				{
					m_login_dialog->name_now =it.key();
				}
			}
			my_para.m_login_privilege = 1;
			m_login_dialog->m_state_label->setText(m_login_dialog->name_now + " Operator login");
			m_login_dialog->m_login_button->setText("Login-out");

			logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " name:" + m_login_dialog->name_now  + " login").toLocal8Bit().toStdString());

           /* QString password_standard = m_qwidget_user->m_userDatabase.value(m_login_dialog->m_user_label->text());

            if (m_login_dialog->m_passward_edit->text() == password_standard)
            {
                my_para.m_login_privilege = 1;
                m_login_dialog->m_state_label->setText("Operator login");
                m_login_dialog->m_login_button->setText("Login-out");

                logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " name:" + m_login_dialog->m_user_label->text() + "login").toLocal8Bit().toStdString());

            }
            else
            {
                QMessageBox::critical(nullptr,"error", m_login_dialog->m_user_label->text() + " wrong password");
            }*/
        }
        if (m_login_dialog->m_qcombox_level->currentIndex()==1)
        {
            bool state = m_qwidget_admin->m_userDatabase.values().contains(m_login_dialog->m_passward_edit->text());
            if(!state)
            {
                QMessageBox::critical(nullptr,"error", "paasord " + m_login_dialog->m_passward_edit->text() + " no exit");
                return;
            }
			
			QMap<QString, QString>::iterator it;
			for (it = m_qwidget_user->m_userDatabase.begin(); it != m_qwidget_user->m_userDatabase.end(); ++it) {
				if (it.value() == m_login_dialog->m_passward_edit->text())
				{
					m_login_dialog->name_now = it.key();
				}
			}
			my_para.m_login_privilege = 2;
			m_login_dialog->m_state_label->setText(m_login_dialog->name_now + " Service login");
			m_login_dialog->m_login_button->setText("Login-out");

			logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " name:" + m_login_dialog->name_now + " login").toLocal8Bit().toStdString());

            //QString password_standard = m_qwidget_admin->m_userDatabase.value(m_login_dialog->m_user_label->text());

           /* if (m_login_dialog->m_passward_edit->text() == password_standard)
            {
                my_para.m_login_privilege = 2;
                m_login_dialog->m_state_label->setText("Service login");
                m_login_dialog->m_login_button->setText("Login-out");

                logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " name:" + m_login_dialog->m_user_label->text() + "login").toLocal8Bit().toStdString());

            }
            else
            {
                QMessageBox::critical(nullptr,"error", m_login_dialog->m_user_label->text() + " wrong password");
            }*/
        }
        if (m_login_dialog->m_qcombox_level->currentIndex()==2)
        {
            if (m_login_dialog->m_passward_edit->text() == m_admin_passeard)
            {
                my_para.m_login_privilege = 3;
                m_login_dialog->m_state_label->setText("Administrator login");
                m_login_dialog->m_login_button->setText("Login Out");
                logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " login").toLocal8Bit().toStdString());
            }
            else
            {
                QMessageBox::critical(nullptr,"error", "admin wrong password");
            }
        }
    }
    else
    {
        if(my_para.m_login_privilege==1)
            logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " name:" + m_login_dialog->name_now + " login out").toLocal8Bit().toStdString());
        if(my_para.m_login_privilege==2)
            logger_user->info((m_login_dialog->m_qcombox_level->currentText() + " login out").toLocal8Bit().toStdString());
        my_para.m_login_privilege = 0;
        m_login_dialog->m_state_label->setText("Login Out");
        m_login_dialog->m_login_button->setText("Login");
        m_login_dialog->m_passward_edit->setText("");

    }

}

void MainWindow::returnMainFrame()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_only_show_state = false;
    }
    m_qdialog_camera->hide();
    m_qdialog_detection->hide();
}

void MainWindow::saveImage(ShowResult result)
{

    QString DirName;
    if (result.m_save_right && result.m_detectin_result == true)
    {

        if(result.m_camera_index==3 || result.m_camera_index ==4)
            DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name + QString::number(result.m_detection_index) + "/OK/";
        else
            DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name  + "/OK/";
        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";
        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image);
    }
    if (result.m_save_wrong && result.m_detectin_result == false) {
        if (result.m_camera_index == 3 || result.m_camera_index == 4)
            DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name + QString::number(result.m_detection_index) + "/NG/";
        else
            DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name  + "/NG/";

        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";

        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image);
    }


    if (result.m_save_wrong_label && result.m_detectin_result == false) {
        if (result.m_camera_index == 3 || result.m_camera_index == 4)
             DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name + QString::number(result.m_detection_index) + "/NGlabel/";
        else
             DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name +  "/NGlabel/";

        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + "label.png";
        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);
    };
    if (result.m_save_ai_ok>0 && result.m_detectin_result == true) {

        if (result.m_camera_index == 3 || result.m_camera_index == 4)
             DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name  + QString::number(result.m_detection_index) + "/okcrop/";
        else
            DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name   + "/okcrop/";

        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + "crop.png";
        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);

    }
    if (result.m_save_ai_ng >0 && result.m_detectin_result == false) {
        if (result.m_camera_index == 3 || result.m_camera_index == 4)
             DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name  + QString::number(result.m_detection_index) + "/ngcrop/";
        else
            DirName = m_save_image_dir  + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name   + "/ngcrop/";

        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + "crop.png";
        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_ai);
    };

}

void MainWindow::showResult(ShowResult result)
{
    uint16_t plc_write_value = 1  ;
//    logger->info("write m_plc_result:" + std::to_string(m_plc_trigger[result.m_camera_index]));

    modbus_write_registers(m_modbus_tcp,m_plc_result[result.m_camera_index],1,&plc_write_value);

    Mat image_draw = result.m_image_draw.clone();
    //m_vector_detection_thread[result.m_camera_index]->m_function->draw(result.m_image,image_draw);
    int fontFace = FONT_HERSHEY_SIMPLEX;
    double fontScale = 2;
    int thickness = 2;
    if(result.m_camera_index<=2)
    {
        QStringList qstringlist = result.m_messgae.split("\n");
        for(int index=0;index<qstringlist.size();index++)
            putText(result.m_image_draw, qstringlist[index].toLocal8Bit().toStdString(), Point(100, index*100+100), fontFace, 1, Scalar(0, 0, 255), thickness);
    }
    else
    {
        QStringList qstringlist = result.m_messgae.split("\n");
        for(int index=0;index<qstringlist.size();index++)
            putText(result.m_image_draw, qstringlist[index].toLocal8Bit().toStdString(), Point(30, index*30+30), fontFace, 1, Scalar(0, 0, 255), thickness);
    }
    saveImage(result);

    /*Mat image_draw= result.m_image_draw;*/
    Mat mat_show ;
    cv::resize(image_draw, mat_show, Size(m_vector_show_qlabel[result.m_camera_index]->width()  ,m_vector_show_qlabel[result.m_camera_index]->height()));

    QImage Qtempimage = matToQImage(mat_show);

//    int64 t2 =  cv::getTickCount();

//    double m_time_use = (t2-t1)*1000/getTickFrequency();

//    m_vector_detection_thread[0]->m_function->sendTcp(m_qtcpsocket);

    QColor color;
    QString message_show2;
    if(result.m_detectin_result == true)
    {
        message_show2 = "OK";
        color={0,255,0};
    }
    else
    {
        message_show2 = "NG";
        color={255,0,0};
    }






    //time
    m_vector_time[result.m_camera_index] = result.m_time_use;
    if (result.m_camera_index == m_camera_number - 1)
    {
        uint time_now = 0;
        for (int i=0;i< m_vector_time.size();i++)
        {
            time_now = time_now + m_vector_time[i];
        }
        m_qlabel_cycle_time->setText(QString::number(time_now)+"ms");
    }


    //数据统计
    if (result.m_output_result.size()>0)
    {
        if(result.m_output_result[0])
        {
            m_result_data[result.m_camera_index].push_back(1);
        }
        else
        {
            m_result_data[result.m_camera_index].push_back(0);
            message_show2 +=  "\n" + QString::number(result.m_times) +  "times:NG";
            color={255,0,0};
        }
    }


   if(m_result_data[0].size()>0 && m_result_data[1].size()>0  && m_result_data[2].size()>0)
   {

       int value=1;
       for (int i = 0; i <= 2; i++)
       {
           int value_now = m_result_data[i].front();
            m_result_data[i].pop_front();
           value = value * value_now;
       }
       if (value == 1)
       {

           uint16_t plc_write_value=1;
           if (m_modbus_tcp != nullptr)
               modbus_write_registers(m_modbus_tcp,m_plc_result1,1,&plc_write_value);
           logger->info("m_plc_result1:" + std::to_string(plc_write_value));

       }
       else
       {
           m_defective_quantity = m_defective_quantity + 1;
           m_qlabel_defective_quantity->setText(QString::number(m_defective_quantity));
           uint16_t plc_write_value=2;
           if (m_modbus_tcp != nullptr)
               modbus_write_registers(m_modbus_tcp,m_plc_result1,1,&plc_write_value);
           logger->info("m_plc_result1:" + std::to_string(plc_write_value));

       }
   }




    if(m_result_data[3].size()>0 && m_result_data[4].size()>0)
        {
            int value=1;
            for (int i = 3; i <=4; i++)
            {
                int value_now = m_result_data[i].front();
                m_result_data[i].pop_front();
                value = value * value_now;
            }
            if (value == 1)
            {
                m_qualified_quantity = m_qualified_quantity + 1;
                m_qlabel_qualified_quantity->setText(QString::number(m_qualified_quantity));
                uint16_t plc_write_value=1;
                if (m_modbus_tcp != nullptr)
                    modbus_write_registers(m_modbus_tcp,m_plc_result2,1,&plc_write_value);
                logger->info("m_plc_result2:" + std::to_string(plc_write_value));


            }
            else
            {
                m_defective_quantity = m_defective_quantity + 1;
                m_qlabel_defective_quantity->setText(QString::number(m_defective_quantity));
                uint16_t plc_write_value=2;
                if (m_modbus_tcp != nullptr)
                    modbus_write_registers(m_modbus_tcp,m_plc_result2,1,&plc_write_value);
                logger->info("m_plc_result2:" + std::to_string(plc_write_value));

            }
        }

    QString message_show  =  result.m_camera_name + QString(":index%1 time%2ms\n").arg(result.m_detection_index).arg(result.m_time_use);


    message_show2  +=  result.m_messgae;

    if (!Qtempimage.isNull())
    {
//        if(result.m_detectin_result)
//            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,color);
//        else
//            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,color);
        m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,color);
    }
    //更新表格
    QString current_time = QDateTime::currentDateTime().toString("yyyy-MM-dd:HH:mm:ss");


    if (result.m_detectin_result == false)
    {
        if (m_show_table_data->rowCount() >= 100)
        {
            m_show_table_data->removeRow(100);
        }
        m_show_table_data->insertRow(0);

        m_show_table_data->setItem(0, 0, new QStandardItem(current_time));
        QString msg = result.m_camera_name + QString(":index%1").arg(result.m_detection_index) + message_show2.remove(QRegExp("[\r\n]"));
        m_show_table_data->setItem(0, 1, new QStandardItem(msg));
    }
}

void MainWindow::startDetection()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = true;
    }
    m_qpushbutton_start_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setDisabled(false);
}

void MainWindow::stopDetection()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = false;
    }
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_start_detection->setDisabled(false);
}

void MainWindow::timerLoadImage()
{
    //相机离线测试
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_image_index++;
        if (m_vector_detection_thread[i]->m_images_path.size() > 0)
        {
            Mat image_read_file;
            image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString());

            if (!image_read_file.empty())
            {
                m_vector_detection_thread[i]->m_camera_index = i;
                m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);
            }
        }
    }
}

void  MainWindow::timerData()
{
    m_qlabel_camera0->setText(QString::number(m_vector_detection_thread[0]->m_ng0_count));
    m_qlabel_camera1->setText(QString::number(m_vector_detection_thread[1]->m_ng0_count));
    m_qlabel_camera2->setText(QString::number(m_vector_detection_thread[2]->m_ng0_count));

    m_qlabel_camera3_0->setText(QString::number(m_vector_detection_thread[3]->m_ng0_count));
    m_qlabel_camera3_1->setText(QString::number(m_vector_detection_thread[3]->m_ng1_count));
    m_qlabel_camera3_2->setText(QString::number(m_vector_detection_thread[3]->m_ng2_count));

    m_qlabel_camera4_0->setText(QString::number(m_vector_detection_thread[4]->m_ng0_count));
    m_qlabel_camera4_1->setText(QString::number(m_vector_detection_thread[4]->m_ng1_count));
    m_qlabel_camera4_2->setText(QString::number(m_vector_detection_thread[4]->m_ng2_count));


    if (m_modbus_tcp != nullptr)
    {
        uint16_t value = m_vector_detection_thread[0]->m_ng0_count;
        modbus_write_registers(m_modbus_tcp,40141,1,&value);
        value = m_vector_detection_thread[1]->m_ng0_count;
        modbus_write_registers(m_modbus_tcp,40142,1,&value);
        value = m_vector_detection_thread[2]->m_ng0_count;
        modbus_write_registers(m_modbus_tcp,40143,1,&value);
        value = m_vector_detection_thread[3]->m_ng0_count;
        modbus_write_registers(m_modbus_tcp,40144,1,&value);
        value = m_vector_detection_thread[3]->m_ng1_count;
        modbus_write_registers(m_modbus_tcp,40145,1,&value);
        value = m_vector_detection_thread[3]->m_ng2_count;
        modbus_write_registers(m_modbus_tcp,40146,1,&value);
        value = m_vector_detection_thread[4]->m_ng0_count;
        modbus_write_registers(m_modbus_tcp,40147,1,&value);
        value = m_vector_detection_thread[4]->m_ng1_count;
        modbus_write_registers(m_modbus_tcp,40148,1,&value);
        value = m_vector_detection_thread[4]->m_ng2_count;
        modbus_write_registers(m_modbus_tcp,40149,1,&value);

    }

    QString qstring_now =QDateTime::currentDateTime().toString("yyyy/MM/dd HH:mm:ss");
    m_qlabel_time->setText(qstring_now);

    QDateTime time_now = QDateTime::currentDateTime();

    // 计算时间差，返回的是一个QTime对象，表示时间间隔

    qint64 diffs = m_qtime_start.secsTo(time_now);
    // 获取小时差值
    qint64 hoursDiff = diffs / 3600;
    m_qlabel_operating_time->setText(QString::number(hoursDiff)+"h");
}

void MainWindow::timerPLC()
{

    uint16_t plc_write_value = 1  ;
    if (m_modbus_tcp != nullptr)
        modbus_write_registers(m_modbus_tcp,m_plc_write,1,&plc_write_value);

    for(int i=0;i< m_camera_number;i++)
    {

        uint16_t plc_trigger_value=0;
        if (m_modbus_tcp != nullptr)
            modbus_read_registers(m_modbus_tcp, m_plc_trigger[i], 1, &plc_trigger_value);


        if(1 == plc_trigger_value )
        {
//            logger->info("read m_plc_trigger:" + std::to_string(m_plc_trigger[i]) + " " +to_string(plc_trigger_value));
            uint16_t plc_write_value = 0  ;
            modbus_write_registers(m_modbus_tcp,m_plc_trigger[i],1,&plc_write_value);

            if (i == 3)
            {
                if (m_vector_detection_thread[i]->m_detection_index == 0)
                {
//					QThread::msleep(300);
//					logger->info(m_vector_camera[i]->m_camera_name.toStdString() + "Sleep 300");
                }
            }
            if (i == 4)
            {
                if (m_vector_detection_thread[i]->m_detection_index == 0)
                {
//					QThread::msleep(300);
//					logger->info(m_vector_camera[i]->m_camera_name.toStdString() + "Sleep 300");
                }
            }

            m_vector_camera[i]->softTrigger();
        }

    }
}

void MainWindow::loadFont()
{
    QFont qfont = loadQFont(*m_settings_para,"");
    QApplication::setFont(qfont);
}

void MainWindow::setFont()
{
    QFont qfont;
    bool ok;
    qfont = QFontDialog::getFont(&ok);

    if(ok){
        QApplication::setFont(qfont);
    }
    saveQFont(*m_settings_para,qfont,"");
}

void MainWindow::storeRecipe()
{
    QString source = m_type_dir + "/" + m_type_name  ;
    QString dest = m_type_dir + "/" + m_store_recipe_dialog.getTypeName()  ;

    if(source == dest)
    {
        return;
    }
    deleteDir(dest);
    bool state = copyFolder(source,dest);
    if(state)
        QMessageBox::information(nullptr,"Store Recipe","Store Recipe OK");
    else
        QMessageBox::information(nullptr,"Store Recipe","Store Recipe NG");
}

void MainWindow::loadRecipe()
{


    QString name = m_load_recipe_dialog.getTypeName();
    if( name == "")
    {
        QMessageBox::information(nullptr,"No Select Receipe" , "No Select Receipe");
        return;
    }
    QMessageBox *msgBox = new QMessageBox(QMessageBox::Question,name, name + " Receipe,Restart", QMessageBox::Yes | QMessageBox::No);


    msgBox->button(QMessageBox::Yes)->setText("Confirm");


    msgBox->button(QMessageBox::No)->setText("Quit");

    int res = msgBox->exec();

    if(QMessageBox::Yes == res)
    {
        m_settings_para->setValue("para/m_type_name" ,name);
        m_settings_para->sync();

        const QString program = QCoreApplication::applicationFilePath();
        const QStringList arguments = QCoreApplication::arguments();
        const QString directory_now = QDir::currentPath();
        QCoreApplication::exit();
        QProcess::startDetached(program, arguments, directory_now);
    }

}
